package com.zhangxin.aiInterview.controller;

import com.zhangxin.aiInterview.annotation.AuthCheck;
import com.zhangxin.aiInterview.common.BaseResponse;
import com.zhangxin.aiInterview.common.ResultUtils;
import com.zhangxin.aiInterview.constant.UserConstant;
import com.zhangxin.aiInterview.model.entity.*;
import com.zhangxin.aiInterview.model.vo.response.ResumeQualityScoreDailyResponse;
import com.zhangxin.aiInterview.model.vo.response.ResumeQualityScoreHistoryResponse;
import com.zhangxin.aiInterview.service.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/echarts")
public class EchartsController {
    @Resource
    private UserService userService;

    @Resource
    private DwsAiInterviewScore1dService dwsAiInterviewScore1dService;
    @Resource
    private DwsDateHrAvgscoreService dwsDateHrAvgscoreService;

    @Resource
    private DwsDateExamAvgscoreService dwsDateExamAvgscoreService;

    @Resource
    private DwsDateFullAvgscoreService dwsDateFullAvgscoreService;

    @Resource
    private DwsUserBehavior1dService dwsUserBehavior1dService;

    @Resource
    private DwsUserBehaviorNdService dwsUserBehaviorNdService;

    @Resource
    private DwsUserInvited1dService dwsUserInvited1dService;

    @Resource
    private DwsUserInvitedTdService dwsUserInvitedTdService;

    @Resource
    private EchartsService echartsService;

    // 招聘者分析相关服务
    @Resource
    private AdsAvgPassRateByCompanyService adsAvgPassRateByCompanyService;

    @Resource
    private AdsCompanyUniversityDistributionService adsCompanyUniversityDistributionService;

    @Resource
    private AdsInterviewCountByCompanyService adsInterviewCountByCompanyService;

    @Resource
    private AdsInterviewCountByCompanyFieldPositionService adsInterviewCountByCompanyFieldPositionService;

    @Resource
    private AdsOnlineInterviewInviteUserCountService adsOnlineInterviewInviteUserCountService;

    @Resource
    private AdsPassRateAndCandidateCountByCompanyPositionService adsPassRateAndCandidateCountByCompanyPositionService;

    @Resource
    private AdsRecruiterInterviewUserCountService adsRecruiterInterviewUserCountService;

    @GetMapping("/user/get/ai/interview/score/1d")
    public BaseResponse<DwsAiInterviewScore1d> getAiInterviewScore1d(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        DwsAiInterviewScore1d dwsAiInterviewScore1d = dwsAiInterviewScore1dService.lambdaQuery()
                .eq(DwsAiInterviewScore1d::getUserId, userId)
                .one();
        return ResultUtils.success(dwsAiInterviewScore1d);
    }

    /**
     * 获取用户HR面试平均成绩趋势
     * 
     * @param request 请求对象
     * @return HR面试平均成绩
     */
    @GetMapping("/user/get/hr/interview/avg/score")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<DwsDateHrAvgscore> getHrInterviewAvgScore(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        DwsDateHrAvgscore hrAvgScore = dwsDateHrAvgscoreService.lambdaQuery()
                .eq(DwsDateHrAvgscore::getUserId, userId)
                .one();
        return ResultUtils.success(hrAvgScore);
    }

    /**
     * 获取用户笔试平均成绩趋势
     * 
     * @param request 请求对象
     * @return 笔试平均成绩
     */
    @GetMapping("/user/get/exam/avg/score")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<DwsDateExamAvgscore> getExamAvgScore(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        DwsDateExamAvgscore examAvgScore = dwsDateExamAvgscoreService.lambdaQuery()
                .eq(DwsDateExamAvgscore::getUserId, userId)
                .one();
        return ResultUtils.success(examAvgScore);
    }

    /**
     * 获取用户全流程面试平均成绩趋势
     * 
     * @param request 请求对象
     * @return 全流程面试平均成绩
     */
    @GetMapping("/user/get/full/process/avg/score")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<DwsDateFullAvgscore> getFullProcessAvgScore(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        DwsDateFullAvgscore fullAvgScore = dwsDateFullAvgscoreService.lambdaQuery()
                .eq(DwsDateFullAvgscore::getUserId, userId)
                .one();
        return ResultUtils.success(fullAvgScore);
    }

    /**
     * 获取用户当天简历评分统计
     * 
     * @param request 请求对象
     * @return 当天简历评分统计
     */
    @GetMapping("/user/get/resume/quality/score/daily")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<List<ResumeQualityScoreDailyResponse>> getResumeQualityScoreDaily(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        // 获取前一天的简历评分统计，包含简历详细信息
        List<ResumeQualityScoreDailyResponse> scoreList = echartsService.getResumeQualityScoreDaily(userId, null);
        return ResultUtils.success(scoreList);
    }

    /**
     * 获取用户历史简历评分统计
     * 
     * @param date    统计日期，格式为yyyy-MM-dd
     * @param request 请求对象
     * @return 历史简历评分统计
     */
    @GetMapping("/user/get/resume/quality/score/history")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<List<ResumeQualityScoreHistoryResponse>> getResumeQualityScoreHistory(
            @RequestParam(required = false) String date,
            HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        // 获取历史简历评分统计，包含简历详细信息
        List<ResumeQualityScoreHistoryResponse> scoreList = echartsService.getResumeQualityScoreHistory(userId, date);
        return ResultUtils.success(scoreList);
    }

    /**
     * 获取用户当日行为统计
     * 
     * @param request 请求对象
     * @return 当日用户行为统计
     */
    @GetMapping("/user/get/user/behavior/daily")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<DwsUserBehavior1d> getUserBehaviorDaily(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        // 获取前一天的日期作为查询条件
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

        DwsUserBehavior1d behavior = dwsUserBehavior1dService.lambdaQuery()
                .eq(DwsUserBehavior1d::getUserId, userId)
                .eq(DwsUserBehavior1d::getCountTime, yesterday)
                .one();
        return ResultUtils.success(behavior);
    }

    /**
     * 获取用户多日行为统计
     * 
     * @param date    统计日期，格式为yyyy-MM-dd
     * @param request 请求对象
     * @return 多日用户行为统计
     */
    @GetMapping("/user/get/user/behavior/multi")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<DwsUserBehaviorNd> getUserBehaviorMultiDay(
            @RequestParam(required = false) String date,
            HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        DwsUserBehaviorNd behavior;
        if (date != null) {
            behavior = dwsUserBehaviorNdService.lambdaQuery()
                    .eq(DwsUserBehaviorNd::getUserId, userId)
                    .eq(DwsUserBehaviorNd::getCountTime, date)
                    .one();
        } else {
            behavior = dwsUserBehaviorNdService.lambdaQuery()
                    .eq(DwsUserBehaviorNd::getUserId, userId)
                    .orderByDesc(DwsUserBehaviorNd::getCountTime)
                    .last("limit 1")
                    .one();
        }
        return ResultUtils.success(behavior);
    }

    /**
     * 获取用户当日接收面试邀请次数
     * 
     * @param request 请求对象
     * @return 当日接收面试邀请次数
     */
    @GetMapping("/user/get/user/invited/daily")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<DwsUserInvited1d> getUserInvitedDaily(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        DwsUserInvited1d invited = dwsUserInvited1dService.lambdaQuery()
                .eq(DwsUserInvited1d::getUserId, userId)
                .one();
        return ResultUtils.success(invited);
    }

    /**
     * 获取用户历史接收面试邀请次数
     * 
     * @param request 请求对象
     * @return 历史接收面试邀请次数
     */
    @GetMapping("/user/get/user/invited/history")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<DwsUserInvitedTd> getUserInvitedHistory(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        DwsUserInvitedTd invited = dwsUserInvitedTdService.lambdaQuery()
                .eq(DwsUserInvitedTd::getUserId, userId)
                .one();
        return ResultUtils.success(invited);
    }

    /**
     * 获取公司平均通过率统计
     *
     * @param companyName 公司名称
     * @return 公司平均通过率随时间变化数据
     */
    @GetMapping("/recruiter/get/pass/rate/by/company")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<List<AdsAvgPassRateByCompany>> getPassRateByCompany(
            @RequestParam("companyName") String companyName) {
        List<AdsAvgPassRateByCompany> passRateList = adsAvgPassRateByCompanyService.lambdaQuery()
                .eq(AdsAvgPassRateByCompany::getCompany_name, companyName)
                .orderByAsc(AdsAvgPassRateByCompany::getDt)
                .list();
        return ResultUtils.success(passRateList);
    }

    /**
     * 获取公司人才来源高校分布
     *
     * @param companyName 公司名称
     * @param date        统计日期，格式为yyyy-MM-dd
     * @return 指定日期公司人才来源高校分布
     */
    @GetMapping("/recruiter/get/university/distribution/by/company")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<List<AdsCompanyUniversityDistribution>> getUniversityDistributionByCompany(
            @RequestParam("companyName") String companyName,
            @RequestParam("date") String date) {
        List<AdsCompanyUniversityDistribution> distributionList = adsCompanyUniversityDistributionService.lambdaQuery()
                .eq(AdsCompanyUniversityDistribution::getCompany_name, companyName)
                .eq(AdsCompanyUniversityDistribution::getDt, date)
                .list();
        return ResultUtils.success(distributionList);
    }

    /**
     * 获取公司面试次数统计
     *
     * @param companyName 公司名称
     * @return 公司面试次数随时间变化数据
     */
    @GetMapping("/recruiter/get/interview/count/by/company")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<List<AdsInterviewCountByCompany>> getInterviewCountByCompany(
            @RequestParam("companyName") String companyName) {
        List<AdsInterviewCountByCompany> interviewCountList = adsInterviewCountByCompanyService.lambdaQuery()
                .eq(AdsInterviewCountByCompany::getCompany_name, companyName)
                .orderByAsc(AdsInterviewCountByCompany::getDt)
                .list();
        return ResultUtils.success(interviewCountList);
    }

    /**
     * 获取公司技术领域和岗位面试统计
     *
     * @param companyName 公司名称
     * @param date        统计日期，格式为yyyy-MM-dd
     * @return 指定日期公司各技术领域和岗位面试统计
     */
    @GetMapping("/recruiter/get/interview/count/by/company/field/position")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<List<AdsInterviewCountByCompanyFieldPosition>> getInterviewCountByCompanyFieldPosition(
            @RequestParam("companyName") String companyName,
            @RequestParam("date") String date) {
        List<AdsInterviewCountByCompanyFieldPosition> fieldPositionList = adsInterviewCountByCompanyFieldPositionService
                .lambdaQuery()
                .eq(AdsInterviewCountByCompanyFieldPosition::getCompany_name, companyName)
                .eq(AdsInterviewCountByCompanyFieldPosition::getDt, date)
                .list();
        return ResultUtils.success(fieldPositionList);
    }

    /**
     * 获取公司线上面试邀请人数统计
     *
     * @param companyName 公司名称
     * @return 公司线上面试邀请人数随时间变化数据
     */
    @GetMapping("/recruiter/get/online/interview/invite/count")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<List<AdsOnlineInterviewInviteUserCount>> getOnlineInterviewInviteCount(
            @RequestParam("company") String companyName) {
        List<AdsOnlineInterviewInviteUserCount> inviteCountList = adsOnlineInterviewInviteUserCountService.lambdaQuery()
                .eq(AdsOnlineInterviewInviteUserCount::getCompany, companyName)
                .orderByAsc(AdsOnlineInterviewInviteUserCount::getDt)
                .list();
        return ResultUtils.success(inviteCountList);
    }

    /**
     * 获取公司各岗位候选人数及通过率
     *
     * @param companyName 公司名称
     * @param date        统计日期，格式为yyyy-MM-dd
     * @return 指定日期公司各岗位候选人数及通过率
     */
    @GetMapping("/recruiter/get/pass/rate/by/company/position")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<List<AdsPassRateAndCandidateCountByCompanyPosition>> getPassRateByCompanyPosition(
            @RequestParam("companyName") String companyName,
            @RequestParam("date") String date) {
        List<AdsPassRateAndCandidateCountByCompanyPosition> passRateList = adsPassRateAndCandidateCountByCompanyPositionService
                .lambdaQuery()
                .eq(AdsPassRateAndCandidateCountByCompanyPosition::getCompany_name, companyName)
                .eq(AdsPassRateAndCandidateCountByCompanyPosition::getDt, date)
                .list();
        return ResultUtils.success(passRateList);
    }

    /**
     * 获取公司面试候选人数统计
     *
     * @param companyName 公司名称
     * @return 公司面试候选人数随时间变化数据
     */
    @GetMapping("/recruiter/get/interview/user/count")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<List<AdsRecruiterInterviewUserCount>> getInterviewUserCount(
            @RequestParam("companyName") String companyName) {
        List<AdsRecruiterInterviewUserCount> userCountList = adsRecruiterInterviewUserCountService.lambdaQuery()
                .eq(AdsRecruiterInterviewUserCount::getCompany_name, companyName)
                .orderByAsc(AdsRecruiterInterviewUserCount::getDt)
                .list();
        return ResultUtils.success(userCountList);
    }
}
